// pages/submit_order/submit_order.js
const http = require('../../utils/http')
const api = require('../../utils/api')
const util = require('../../utils/util')
const ui = require('../../utils/ui')

import Dialog from "../../components/dialog/dialog"

var weekDay = ["周天", "周一", "周二", "周三", "周四", "周五", "周六"]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    status: 1,
    title: "提交订单",
    itemId: 0, //房间ID
    date: null, //当前选中时间
    roomData: null, //服务器返回数据
    dateList: null,
    dateSelectedIndex: 0,
    sliderValue: 4,
    totalPrice: 0,
    totalPriceMember: 0,
    endTime: "",
    multiArray: [
      ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23'], 
      ['00', '10', '20', '30', '40', '50']
    ],
    multiIndex: [0, 0],
    minArrayCopy: [],
  },

  toPurchase() {
    let tel = getApp().globalData.tel
    if (tel == "" || tel == null) {
      wx.navigateTo({
        url: '/pages/login/login',
      })
    }
    else {
      wx.navigateTo({
        url: '/pages/purchase/purchase',
      })
    }
  },

  onInput(e) {
    let value = e.detail.value
    if (value == 3) {
      ui.showToast({
          title: '温馨提示: 房间预订3小时起订',
      })
    }
    var hour = parseInt(this.data.multiArray[0][this.data.multiIndex[0]])+parseInt(value)
    var min = parseInt(this.data.multiArray[1][this.data.multiIndex[1]])
    if ((value/0.5)%2) {
      min = parseInt(this.data.multiArray[1][this.data.multiIndex[1]])+30
    }
    var date = new Date(new Date().setHours(hour, min, 0, 0))
    var hour_end = date.getHours()
    var min_end = date.getMinutes().toString().padStart(2, "0")
    var endTimeStr = hour_end+":"+min_end
    const price = this.data.roomData.item.price
    const memberPrice = this.data.roomData.item.memberPrice ?? price
    this.setData({
      endTime: endTimeStr,
      sliderValue: value,
      totalPrice: util.keepTwoDecimal(parseFloat(price) * parseFloat(value)),
      totalPriceMember: util.keepTwoDecimal(parseFloat(memberPrice) * parseFloat(value)),
    })
  },

  checkStartDate(unReserveTimes) {
    //获取当前时间
    var now = new Date()
    var stamp = now.getTime()
    //当前选中是否为今天
    if (this.data.date.getDate() > now.getDate()) {
      now = this.data.date
      stamp = now.getTime()
    }

    let busy = false
    let startTime = stamp
    for (const index in unReserveTimes) {
      let item = unReserveTimes[index]
      let bt = new Date(parseInt(item.reserveStartTime))
      let et = new Date(parseInt(item.reserveEndTime))

      if (bt.getTime()-stamp > 60*60*1000 && !busy) {
        break
      }
      if (stamp-20*60*1000 < et.getTime()) {
        //延长20分钟
        busy = true
        startTime = et.getTime()+20*60*1000
        //查看下一个
        if (unReserveTimes.length-1 > parseInt(index)) {
          let next = unReserveTimes[parseInt(index)+1]
          let nbt = new Date(parseInt(next.reserveStartTime))
          let net = new Date(parseInt(next.reserveEndTime))
          if (nbt.getTime() - startTime > 60*60*1000) {
            //查看是否够1小时游戏时间
            break
          }
          else {
            startTime = net.getTime()+20*60*1000
          }
        }
      }
    }

    let startDate = new Date(startTime)
    let hour = startDate.getHours()
    let min = startDate.getMinutes()
    min = Math.ceil(min/10)*10

    if(min == 60 && hour == 23) {
      startDate.setHours(0, 0, 0, 0)
      startDate.setDate(startDate.getDate()+1)
      hour = 0
      min = 0
    }
    else if (min == 60) {
      hour += 1
      min = 0
    }

    let sd_0 =  new Date(startDate.setHours(0, 0, 0, 0))
    let nd_0 = new Date(now.setHours(0, 0, 0, 0))

    //是否切换日期
    if (sd_0 > nd_0) {
      let after = (sd_0.getTime() - nd_0.getTime()) / (1000 * 3600 * 24)
      //currentTarget.dataset.indexData
      this.dateChoose({
        currentTarget: {
          dataset: {
            indexData: after
          }
        }
      })
    }
    
    min = (""+min).padStart(2, "0")
    var minIndex = min.substr(0,1)
    var hourEnd = hour+this.data.sliderValue
    if (hourEnd >= 24) {
      hourEnd = hourEnd - 24
    }
    //由于每天可选时间不一样，重新装填时间
    var hour_index = parseInt(hour)
    var min_index = parseInt(minIndex)
    var hour_array = []
    var min_array = []
    for (let i = hour_index; i < 24; i++) {
      hour_array.push(i+"")
    }
    for (let i = min_index; i < 6; i++) {
      min_array.push(i+"0")
    }
    this.setData({
      multiArray: [hour_array, min_array],
      multiIndex: [0, 0],
      minArrayCopy: min_array,
      endTime: hourEnd+":"+min
    })

  },

  requestData() {
    this.setData({
      date: new Date(new Date().setHours(0, 0, 0, 0)),
    })
    http.request({
      showLoading: true,
      url: api.occupied,
      data: {
        memberId: getApp().globalData.memberId,
        itemId: this.data.itemId,
      }
    }).then(res=>{
      //处理轮播数据
      let data = res.data.result
      if (data.item.pictures == null) {
        data.item.pictures = ""
      }
      let images = data.item.pictures.split(',')
      data.item.pictures = images
      //测试数据
      // data.unReserveTimes = [
      //   {reserveStartTime: new Date('2022-11-23 20:07:00').getTime(), reserveEndTime: new Date('2022-11-23 23:07:00').getTime()},
      //   {reserveStartTime: new Date('2022-11-25 10:20:00').getTime(), reserveEndTime: new Date('2022-11-25 11:20:00').getTime()},
      // ]
      const price = data.item.price
      const memberPrice = data.item.memberPrice ?? price
      this.setData({
        roomData: data,
        totalPrice: util.keepTwoDecimal(parseFloat(price) * parseFloat(this.data.sliderValue)),
        totalPriceMember: util.keepTwoDecimal(parseFloat(memberPrice) * parseFloat(this.data.sliderValue)),
      })
      this.checkStartDate(data.unReserveTimes)
    }).catch(err=>{
      console.log(err)
    });
  },

  initDateList() {
    var list = []
    var today = new Date(new Date().setHours(0, 0, 0, 0))
    var todayStr = (today.getMonth() + 1).toString().padStart(2, "0") +"-"+ today.getDate().toString().padStart(2, "0")
    list.push({"dateNum": todayStr, "dateStr": weekDay[today.getDay()], "date": today, "isSelect":true})
    for(var i = 1; i < 5; i++) {
      var day = new Date(new Date().setDate(today.getDate()+i))
      day.setHours(0, 0, 0, 0)
      var dayStr = (day.getMonth() + 1).toString().padStart(2, "0") +"-"+ day.getDate().toString().padStart(2, "0")
      list.push({"dateNum": dayStr, "dateStr": weekDay[day.getDay()], "date": day, "isSelect":false})
    }
    this.setData({
      dateList: list,
    })
  },

  bindMultiPickerColumnChange(e) {
    let col = e.detail.column
    let val = e.detail.value
    let hour_index_origin = this.data.multiIndex[0]
    let hour_array = this.data.multiArray[0]
    let multi_index_hour = this.data.multiIndex[0]
    if (col == 0 && val != hour_index_origin) {
      if (val > 0) {
        this.setData({
          multiArray: [hour_array, ['00', '10', '20', '30', '40', '50']],
        })
      }
      else {
        this.setData({
          multiArray: [hour_array, this.data.minArrayCopy],
        })
      }
    }
    if (col == 0) {
      //切换小时分钟切换至第一个
      this.setData({
        multiIndex: [val, 0]
      })
    }
    else {
      this.setData({
        multiIndex: [multi_index_hour, val]
      })
    }
    this.bindMultiPickerChange({
      detail: {
        value: [this.data.multiIndex[0], this.data.multiIndex[1]]
      }
    })
  },

  bindMultiPickerChange: function (e) {
    var hour = this.data.multiArray[0][e.detail.value[0]]
    var min = this.data.multiArray[1][e.detail.value[1]]
    var hourEnd = parseInt(hour)+this.data.sliderValue
    if (hourEnd >= 24) {
      hourEnd = hourEnd - 24
    }
    const price = this.data.roomData.item.price
    const memberPrice = this.data.roomData.item.memberPrice ?? price
    this.setData({
      multiIndex: e.detail.value,
      totalPrice: util.keepTwoDecimal(parseFloat(price) * parseFloat(this.data.sliderValue)),
      totalPriceMember: util.keepTwoDecimal(parseFloat(memberPrice) * parseFloat(this.data.sliderValue)),
      endTime: hourEnd+":"+min
    })
  },

  dateChoose: function (event) {
    var index = event.currentTarget.dataset.indexData
    for (var i = 0; i < this.data.dateList.length; i++) {
      var _ab = "dateList["+i+"].isSelect"//修改
      var temp = event.currentTarget.dataset.indexData == i
      // console.log("index:" + index)
      // console.log("i:" + i)
      // console.log("temp:" + temp)
      this.setData({
        [_ab] : temp
      })
    }
    this.setData({
      date: this.data.dateList[index].date,
      dateSelectedIndex: index,
    })
    this.checkStartDate(this.data.roomData.unReserveTimes)
    // this.requestData()
  },

  showConfirmDialog(event) {
    Dialog.confirm({
      selector: "#confirm-dialog",
      title: "确认提示",
      cancelButtonText: "取消",
      confirmButtonText: "确定",
      confirmCallback:() => {
        this.submit()
      },
    });
  },

  _preview(event) {
    let currentUrl = event.currentTarget.dataset.src
    wx.previewImage({
      current: currentUrl,
      urls: this.data.pictures.length > 0 ? this.roomData.pictures : [currentUrl]
    })
  },

  submit: function (event) {
    var hour = parseInt(this.data.multiArray[0][this.data.multiIndex[0]])
    var min = parseInt(this.data.multiArray[1][this.data.multiIndex[1]])

    const durationTime = parseFloat(this.data.sliderValue)
    
    if(durationTime < 1){
      wx.showToast({
        title: '订单时长至少为1小时',
        icon: 'none',
        duration: 1500,
        mask:true
        })
        return;
    }

    const itemId = this.data.itemId
    const memberId = getApp().globalData.memberId

    const reserveDate = util.formatTimeFromStamp(this.data.date.getTime())
    const startDate = util.formatTimeFromStamp(this.data.date.setHours(hour, min, 0, 0))
    const endDate = util.formatTimeFromStamp(this.data.date.setHours(hour, min+parseFloat(this.data.sliderValue*60), 0, 0))
    let totalPrice = this.data.totalPrice
    // if (this.data.roomData.isMember) {
    //   totalPrice = this.data.totalPriceMember
    // }
    
    http.request({
      showLoading: true,
      url: api.book,
      method: "POST",
      data: {
        durationTime,
        endDate,
        itemId,
        memberId,
        reserveDate,
        startDate,
        totalPrice,
      }
    }).then(res=>{
      console.log(res)
      let data = res.data.result
      if (data.state) {
        let params = {
          "isRenewal": false,
          "oid": data.tradeId,
          "name": this.data.roomData.item.itemName,
          "desc": this.data.roomData.item.describes,
          "url": encodeURIComponent(this.data.roomData.item.itemLogo),
          "time": startDate+" 至 "+endDate, 
          "duration": durationTime, 
          "price": this.data.totalPrice,
          "memberPrice": this.data.totalPriceMember
        } 
        this.toOrderDetail(params)
      }
      else {
        ui.showToast({
          // icon: "error",
          title: data.msg ?? "该时间已被预订",
        })
      }
    }).catch(err=>{
      console.log(err)
    });
  },

  toOrderDetail(params) {  
    wx.navigateTo({
      url: '/pages/order_detail/order_detail'+util.paramsWrap(params),
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      itemId: options.itemId,
      status: options.status
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.initDateList()
    this.requestData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})